package com.zhongketech.sunflower.transport.model;

import java.util.List;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.SqlUtils;
import de.greenrobot.dao.internal.DaoConfig;
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

import com.zhongketech.sunflower.transport.model.User;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/** 
 * DAO for table USER.
*/
public class UserDao extends AbstractDao<User, String> {

    public static final String TABLENAME = "USER";

    /**
     * Properties of entity User.<br/>
     * Can be used for QueryBuilder and for referencing column names.
    */
    public static class Properties {
        public final static Property Id = new Property(0, String.class, "id", true, "ID");
        public final static Property Visible_id = new Property(1, String.class, "visible_id", false, "VISIBLE_ID");
        public final static Property Role = new Property(2, String.class, "role", false, "ROLE");
        public final static Property Phone = new Property(3, String.class, "phone", false, "PHONE");
        public final static Property Password = new Property(4, String.class, "password", false, "PASSWORD");
        public final static Property Gender = new Property(5, String.class, "gender", false, "GENDER");
        public final static Property Name = new Property(6, String.class, "name", false, "NAME");
        public final static Property Birthday = new Property(7, String.class, "birthday", false, "BIRTHDAY");
        public final static Property Avatar_url = new Property(8, String.class, "avatar_url", false, "AVATAR_URL");
        public final static Property MyParentsId = new Property(9, long.class, "myParentsId", false, "MY_PARENTS_ID");
    };

    private DaoSession daoSession;

    private Query<User> parents_ParentsQuery;

    public UserDao(DaoConfig config) {
        super(config);
    }
    
    public UserDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
        this.daoSession = daoSession;
    }

    /** Creates the underlying database table. */
    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "'USER' (" + //
                "'ID' TEXT PRIMARY KEY NOT NULL ," + // 0: id
                "'VISIBLE_ID' TEXT," + // 1: visible_id
                "'ROLE' TEXT," + // 2: role
                "'PHONE' TEXT," + // 3: phone
                "'PASSWORD' TEXT," + // 4: password
                "'GENDER' TEXT," + // 5: gender
                "'NAME' TEXT," + // 6: name
                "'BIRTHDAY' TEXT," + // 7: birthday
                "'AVATAR_URL' TEXT," + // 8: avatar_url
                "'MY_PARENTS_ID' INTEGER NOT NULL );"); // 9: myParentsId
    }

    /** Drops the underlying database table. */
    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'USER'";
        db.execSQL(sql);
    }

    /** @inheritdoc */
    @Override
    protected void bindValues(SQLiteStatement stmt, User entity) {
        stmt.clearBindings();
        stmt.bindString(1, entity.getId());
 
        String visible_id = entity.getVisible_id();
        if (visible_id != null) {
            stmt.bindString(2, visible_id);
        }
 
        String role = entity.getRole();
        if (role != null) {
            stmt.bindString(3, role);
        }
 
        String phone = entity.getPhone();
        if (phone != null) {
            stmt.bindString(4, phone);
        }
 
        String password = entity.getPassword();
        if (password != null) {
            stmt.bindString(5, password);
        }
 
        String gender = entity.getGender();
        if (gender != null) {
            stmt.bindString(6, gender);
        }
 
        String name = entity.getName();
        if (name != null) {
            stmt.bindString(7, name);
        }
 
        String birthday = entity.getBirthday();
        if (birthday != null) {
            stmt.bindString(8, birthday);
        }
 
        String avatar_url = entity.getAvatar_url();
        if (avatar_url != null) {
            stmt.bindString(9, avatar_url);
        }
        stmt.bindLong(10, entity.getMyParentsId());
    }

    @Override
    protected void attachEntity(User entity) {
        super.attachEntity(entity);
        entity.__setDaoSession(daoSession);
    }

    /** @inheritdoc */
    @Override
    public String readKey(Cursor cursor, int offset) {
        return cursor.getString(offset + 0);
    }    

    /** @inheritdoc */
    @Override
    public User readEntity(Cursor cursor, int offset) {
        User entity = new User( //
            cursor.getString(offset + 0), // id
            cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // visible_id
            cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // role
            cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // phone
            cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // password
            cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // gender
            cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // name
            cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7), // birthday
            cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8), // avatar_url
            cursor.getLong(offset + 9) // myParentsId
        );
        return entity;
    }
     
    /** @inheritdoc */
    @Override
    public void readEntity(Cursor cursor, User entity, int offset) {
        entity.setId(cursor.getString(offset + 0));
        entity.setVisible_id(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
        entity.setRole(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
        entity.setPhone(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
        entity.setPassword(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
        entity.setGender(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
        entity.setName(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6));
        entity.setBirthday(cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7));
        entity.setAvatar_url(cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8));
        entity.setMyParentsId(cursor.getLong(offset + 9));
     }
    
    /** @inheritdoc */
    @Override
    protected String updateKeyAfterInsert(User entity, long rowId) {
        return entity.getId();
    }
    
    /** @inheritdoc */
    @Override
    public String getKey(User entity) {
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    /** @inheritdoc */
    @Override    
    protected boolean isEntityUpdateable() {
        return true;
    }
    
    /** Internal query to resolve the "parents" to-many relationship of Parents. */
    public List<User> _queryParents_Parents(long myParentsId) {
        synchronized (this) {
            if (parents_ParentsQuery == null) {
                QueryBuilder<User> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.MyParentsId.eq(null));
                parents_ParentsQuery = queryBuilder.build();
            }
        }
        Query<User> query = parents_ParentsQuery.forCurrentThread();
        query.setParameter(0, myParentsId);
        return query.list();
    }

    private String selectDeep;

    protected String getSelectDeep() {
        if (selectDeep == null) {
            StringBuilder builder = new StringBuilder("SELECT ");
            SqlUtils.appendColumns(builder, "T", getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T0", daoSession.getSchoolDao().getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T1", daoSession.getClassesDao().getAllColumns());
            builder.append(" FROM USER T");
            builder.append(" LEFT JOIN SCHOOL T0 ON T.'ID'=T0.'USER_KEY'");
            builder.append(" LEFT JOIN CLASSES T1 ON T.'ID'=T1.'USER_KEY'");
            builder.append(' ');
            selectDeep = builder.toString();
        }
        return selectDeep;
    }
    
    protected User loadCurrentDeep(Cursor cursor, boolean lock) {
        User entity = loadCurrent(cursor, 0, lock);
        int offset = getAllColumns().length;

        School school = loadCurrentOther(daoSession.getSchoolDao(), cursor, offset);
         if(school != null) {
            entity.setSchool(school);
        }
        offset += daoSession.getSchoolDao().getAllColumns().length;

        Classes classes = loadCurrentOther(daoSession.getClassesDao(), cursor, offset);
         if(classes != null) {
            entity.setClasses(classes);
        }

        return entity;    
    }

    public User loadDeep(Long key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder(getSelectDeep());
        builder.append("WHERE ");
        SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
        String sql = builder.toString();
        
        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);
        
        try {
            boolean available = cursor.moveToFirst();
            if (!available) {
                return null;
            } else if (!cursor.isLast()) {
                throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
            }
            return loadCurrentDeep(cursor, true);
        } finally {
            cursor.close();
        }
    }
    
    /** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
    public List<User> loadAllDeepFromCursor(Cursor cursor) {
        int count = cursor.getCount();
        List<User> list = new ArrayList<User>(count);
        
        if (cursor.moveToFirst()) {
            if (identityScope != null) {
                identityScope.lock();
                identityScope.reserveRoom(count);
            }
            try {
                do {
                    list.add(loadCurrentDeep(cursor, false));
                } while (cursor.moveToNext());
            } finally {
                if (identityScope != null) {
                    identityScope.unlock();
                }
            }
        }
        return list;
    }
    
    protected List<User> loadDeepAllAndCloseCursor(Cursor cursor) {
        try {
            return loadAllDeepFromCursor(cursor);
        } finally {
            cursor.close();
        }
    }
    

    /** A raw-style query where you can pass any WHERE clause and arguments. */
    public List<User> queryDeep(String where, String... selectionArg) {
        Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
        return loadDeepAllAndCloseCursor(cursor);
    }
 
}
